import * as THREE from 'three'
import createApp from '../../core'

function createEllipseCurve (dom: HTMLElement) {
  const { camera, scene, gui } = createApp(dom)
  camera.position.set(0, 0, 100)
  camera.lookAt(scene.position)

  const axes = new THREE.AxesHelper(100)
  scene.add(axes)
  const { aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation, color } = data
  const curve = new THREE.EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation)
  const points = curve.getPoints(50)
  const geometry = new THREE.BufferGeometry().setFromPoints(points)
  const material = new THREE.LineBasicMaterial({ color })
  const line = new THREE.Line(geometry, material)

  scene.add(line)

  function changeMesh () {
    generateGeometry(line)
  }

  gui.add(data, 'aX', -100, 100).onChange(changeMesh)
  gui.add(data, 'aY', -100, 100).onChange(changeMesh)
  gui.add(data, 'xRadius', 0, 100).onChange(changeMesh)
  gui.add(data, 'yRadius', 0, 100).onChange(changeMesh)
  gui.add(data, 'aStartAngle', 0, Math.PI * 2).onChange(changeMesh)
  gui.add(data, 'aEndAngle', 0, Math.PI * 2).onChange(changeMesh)
  gui.add(data, 'aClockwise').onChange(changeMesh)
  gui.add(data, 'aRotation', 0, Math.PI * 2).onChange(changeMesh)
  gui.addColor(data, 'color').onChange(() => {
    material.color = new THREE.Color(data.color)
  })
}

const data = {
  aX: 0,
  aY: 0,
  xRadius: 50,
  yRadius: 30,
  aStartAngle: 0,
  aEndAngle: Math.PI * 2,
  aClockwise: false,
  aRotation: 0,
  color: 0xff0000
}

function generateGeometry (mesh: THREE.Line) {
  const { aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation } = data
  const curve = new THREE.EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation)
  const points = curve.getPoints(50)
  const geometry = new THREE.BufferGeometry().setFromPoints(points)
  mesh.geometry.dispose()
  mesh.geometry = geometry
}

export {
  createEllipseCurve
}
